<template>
	<view class="">
		<view class="index">
			<view class="slideshow">
				<!-- <image src="../../static/bg.jpg" class="bg" mode=""></image> -->
				<!-- <view class="bg">
					
				</view> -->
				<!-- 海报弹窗 -->
				<u-popup v-model="postShow" height="800rpx" width="500rpx" mode="center" closeable>
					<image :src="postImg" style="width: 648rpx; height: 900rpx"></image>
					<button class="likeBtn joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" @click="saveImage">
						保存海报
					</button>
				</u-popup>
				<view class="ToddayRenwu">
					<view class="title"> {{ data.nickName }}的打卡照片 </view>
					<image style="width: 100%; height: 260px; background-color: #eeeeee" mode="aspectFill" :src="img" @click="lookImage(img)"></image>
					<view style="padding: 48rpx 0;">
						<image class="avatarUrl" v-for="(item, index) in likeList" :key="index" :src="item.avatarUrl" mode=""></image>
					</view>
				</view>
			</view>
			<view class="indexBody">
				<view class="inputBar">
					<button v-if="!isOwn" :disabled="islikeBtn" open-type="getUserInfo" @getuserinfo="getuserinfo" class="likeBtn joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}"
					 type="default">
						已有{{ data.likeOpenid.length }}人为他点赞
					</button>
					<button v-else open-type="share" class="likeBtn joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" type="default">
						邀请朋友点赞
					</button>
					<button class="likeBtn joinBtn" :style="{backgroundColor:system.color,color:system.frontColor}" @click="this.$data.postShow = true">
						分享海报
					</button>
					<view class="wanfa" @click="this.$data.wanfaShow = true">
						查看玩法说明
					</view>
				</view>
			</view>
			
		</view>
		<!-- 玩法弹窗 -->
		<u-popup v-model="wanfaShow" mode="center" closeable>
			<!-- <image src="/static/wanfa.jpg" style="width: 648rpx;height: 1152rpx;" mode=""></image> -->
			<u-parse :html="system.wanfa" :tag-style="style"></u-parse>
		</u-popup>
		<!-- 海报画布 -->
		<painter @imgOK="onImgOk" @imgErr="onImgErr" widthPixels="1080" :customStyle="customStyle" :palette="template" />
	</view>
</template>

<script>
	import Card from "./card.js";
	export default {
		data() {
			return {
				toadySignId: "", //打卡_id
				isOwn: false, //是否为打卡创建者
				data: [], //打卡数据
				postShow: false, //海报弹框开关
				img: "",
				islikeBtn: false, //是否为点赞按钮开关
				likeList: [], //点赞用户数据
				// 海报参数
				cardInfo: {
					inc: "1", //打卡总次数
					m: "1", //月份
					d: "1", //天数
					post: "", //二维码
				},
				customStyle: "visibility:hidden;z-index:-1;position: absolute;top: -10000px;", //海报画布自定义样式,完全隐藏画布
				template: "", //海报画布palette
				postImg: "", //海报图地址
				system: [],
				nameID: 'jmwq',
				style: {
					// 字符串的形式
					img: 'max-width: 550rpx'
				},
				wanfaShow: false, //是否显示玩法介绍
			};
		},
		onLoad(query) {
			console.log(query);
			this.$data.toadySignId = query.toadySignId
			//获取
			wx.cloud.callFunction({
				name: 'echo',
				data: {
					action: "getSystem",
					nameID: this.$data.nameID
				}
			}).then(res => {
				uni.setStorageSync('system', res.result.data[0])
				this.$data.system = uni.getStorageSync('system')
				this.$data.system.frontColor = this.$data.system.frontColor ? '#000000' : '#ffffff'
				wx.setNavigationBarTitle({title:this.$data.system.name})
				wx.setNavigationBarColor({
				   frontColor:  this.$data.system.frontColor,
				  backgroundColor: this.$data.system.color,
				  animation: {
				    duration: 400,
				    timingFunc: 'easeIn'
				  }
				})
				
				//获取打卡详情
				wx.cloud
					.callFunction({
						name: "echo",
						data: {
							action: "getUserSignData",
							id: this.$data.toadySignId,
						},
					})
					.then((res) => {
						this.$data.data = res.result.data[0];
						this.$data.img = res.result.data[0].fileID;
						//如果没有二维码则生成二维码
						if (res.result.data[0].post == "") {
							wx.cloud
								.callFunction({
									name: "echo",
									data: {
										action: "getWXACode",
										id: this.$data.toadySignId,
										openId: res.result.data[0]._openid,
									},
								})
								.then((res) => {
									this.downloadFile(res.result)
								});
						} else {
							this.downloadFile(res.result.data[0].post)
						}
						//判断是否为打卡拥有者
						if (res.result.data[0]._openid == uni.getStorageSync("openid")) {
							this.$data.isOwn = true;
							this.$data.islikeBtn = true;
						} else {
							this.$data.isOwn = false;
							//判断好友是否已打卡
							for (var i = 0; i < this.$data.data.likeOpenid.length; i++) {
								if (uni.getStorageSync("openid") == this.$data.data.likeOpenid[i]) {
									this.$data.islikeBtn = true;
								}
							}
						}
						//整理打卡用户信息
						for (var i = 0; i < this.$data.data.likeList.length; i++) {
							this.$data.likeList.push(JSON.parse(this.$data.data.likeList[i]));
						}
					})
					.catch((err) => {
						console.log(err);
					});
			})

		},
		onShareAppMessage(res) {
			if (res.from === "button") {
				// 来自页面内分享按钮
				console.log(res.target);
			}
			return {
				title: "我正在芥末围棋打卡，快来给我点个赞",
				path: `/pages/index/share?toadySignId=${this.$data.toadySignId}`,
			};
		},
		methods: {
			downloadFile(fileID) {
				console.log(fileID)
				wx.cloud.downloadFile({
					fileID: fileID, // 文件 ID
					success: (res) => {
						// 返回临时文件路径
						//整理cardInfo
						this.$data.cardInfo.post = res.tempFilePath;
						this.$data.cardInfo.m = (
							new Date(this.$data.data.signTime).getMonth() + 1
						).toString();
						this.$data.cardInfo.d = new Date(this.$data.data.signTime)
							.getDate()
							.toString();
						//获取用户打卡次数
						wx.cloud
							.callFunction({
								name: "echo",
								data: {
									action: "getUserInc",
									useropenid: this.$data.data._openid,
								},
							})
							.then((res) => {
								this.$data.cardInfo.inc = (
									res.result.data[0].userInc + 1
								).toString();
								this.initData();
							});
					},
					fail: console.error,
				});
			},
			lookImage(e) {
				//预览打卡照片
				wx.previewImage({
					urls: [e], // 需要预览的图片http链接列表
				});
			},
			getuserinfo(e) {
				console.log(e.detail.userInfo);
				var userInfo = e.detail.userInfo;
				if (e.detail.rawData == undefined) {
					wx.showToast({
						title: "请授权登陆！",
						icon: "none",
					});
				} else {
					//判断曾经是否保存openid
					if (uni.getStorageSync("openid")) {
						this.dianzan(e.detail.rawData);
					} else {
						//获取用户openid
						wx.cloud.callFunction({
							name: "login",
							success: (res) => {
								uni.setStorageSync("openid", res.result.openid);
								this.dianzan(e.detail.rawData);
							},
						});
					}
				}
			},
			dianzan(userInfo) {
				wx.cloud
					.callFunction({
						name: "echo",
						data: {
							action: "like",
							id: this.$data.toadySignId,
							likeUserData: userInfo,
							likeUserOpenid: uni.getStorageSync("openid")
						},
					})
					.then((res) => {
						if (res.result.count.stats.updated == 1) {
							wx.showToast({
								title: "点赞成功！",
								icon: "none"
							});
							this.$data.islikeBtn = true;
							this.$data.data.likeOpenid.push(uni.getStorageSync("openid"));
							this.$data.likeList.push(userInfo);
						}
						//判断点赞次数是否达到
						if (res.result.sendResult.data[0].likeOpenid.length == this.$data.system.shenheNum) {
							//发送模板消息
							this.sendSubscribeMessageLike(
								res.result.sendResult.data[0]._openid
							);
						}
					})
					.catch((err) => {
						console.log(err);
					});
			},
			sendSubscribeMessageLike(e) {
				//整理时间戳
				var getFullYear = new Date().getFullYear();
				var getMonth = new Date().getMonth() + 1;
				var getDate = new Date().getDate();
				var getHours = new Date().getHours();
				var getMinutes = new Date().getMinutes();
				var getSeconds = new Date().getSeconds();
				if (getMonth < 10) {
					getMonth = "0" + getMonth;
				}
				if (getDate < 10) {
					getDate = "0" + getDate;
				}
				if (getHours < 10) {
					getHours = "0" + getHours;
				}
				if (getMinutes < 10) {
					getMinutes = "0" + getMinutes;
				}
				if (getSeconds < 10) {
					getSeconds = "0" + getSeconds;
				}

				var data = {
					action: "sendSubscribeMessageLike",
					_openid: e,
					_id: this.$data.toadySignId,
					date: `${getFullYear}年${getMonth}月${getDate}日 ${getHours}:${getMinutes}:${getSeconds}`,
				};
				var data2 = {
					action: "shenhe",
					_id: this.$data.toadySignId
				};
				console.log(data);
				wx.cloud
					.callFunction({
						name: "echo",
						data,
					})
					.then((res) => {});
				wx.cloud
					.callFunction({
						name: "echo",
						data: data2,
					})
					.then((res) => {});

				this.userInc(e);
			},
			userInc(e) {
				var openid = e;
				//打卡次数加1
				wx.cloud
					.callFunction({
						name: "echo",
						data: {
							action: "userInc",
							useropenid: openid,
						},
					})
					.then((res) => {
						console.log(res);
					})
					.catch((err) => {
						console.log(err);
					});
			},
			initData() {
				uni.showLoading({
					title: "生成海报中",
					mask: true,
				});
				this.template = new Card().do(this.$data.cardInfo);
			},
			onImgOk(e) {
				uni.hideLoading();
				console.log(e);
				this.$data.postImg = e.detail.path;
				//this.$data.customStyle = "display:none";
				//this.$data.postShow = true;
			},
			imgErr(e) {
				uni.hideLoading();
				uni.showModal({
					title: "提示",
					content: "生成海报失败",
					showCancel: false,
				});
				console.log(e);
			},
			saveImage() {
				//长按保存
				uni.showLoading({
					title: "保存中",
					mask: true,
				});
				wx.saveImageToPhotosAlbum({
					filePath: this.$data.postImg,
					success: (res) => {
						uni.hideLoading();
						uni.showModal({
							title: "保存成功",
							content: "图片已成功保存到相册，快去分享到您的圈子吧",
							showCancel: false,
						});
					},
					fail: (err) => {
						console.log(err);
						uni.hideLoading();
					},
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.avatarUrl {
		height: 100rpx;
		width: 100rpx;
		border-radius: 50%;
		margin: 10rpx;
	}

	.slideshow {
		padding: 48rpx;
	}

	.dianzan {
		text-align: center;
	}

	.joinBtn {
		margin: 24rpx 100rpx;
		font-size: 28rpx;
		line-height: 88rpx;
	}

	.indexBody {
		padding: 0 48rpx;
		position: fixed;
		bottom: -1rpx;
		width: 100%;
	    /* background: linear-gradient(top, rgba(225,225,225,0.8) 0%,rgba(225,225,225,1) 15%,rgba(225,225,225,1) 100%) */
		/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+0,ffffff+100&0+0,1+20 */
		background: -moz-linear-gradient(top, rgba(255,255,255,0.8) 0%, rgba(255,255,255,1) 20%, rgba(255,255,255,1) 100%); /* FF3.6-15 */
		background: -webkit-linear-gradient(top, rgba(255,255,255,0.8) 0%,rgba(255,255,255,1) 20%,rgba(255,255,255,1) 100%); /* Chrome10-25,Safari5.1-6 */
		background: linear-gradient(to bottom, rgba(255,255,255,0.8) 0%,rgba(255,255,255,1) 20%,rgba(255,255,255,1) 100%); /* W3C, IE10+, FF16+, Chrome20+, Opera12+, Safari7+ */
		filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#ffffff',GradientType=0 ); /* IE6-9 */
	}
	
	.inputBar {
		margin-bottom: 30px;
		margin-top: 40px;
		width: 654rpx;
	}

	.title {
		text-align: center;
		font-size: 40rpx;
		margin-bottom: 48rpx;
		font-weight: 500;
	}
	.wanfa {
		font-size: 28rpx;
		text-align: center;
		color: #d0d0d0;
	}
	
	.wanfaicon {
		display: inline-block;
	}
</style>
